﻿

CREATE proc CashSale.GetInvoiceNumber
@CashSaleID	int,
@UserID		int
as
begin
	set nocount on

	declare	@now		datetime2(7)	= sysdatetime(),
			@InvoiceNo	int				= 0,
			@logText	nvarchar(150),
			@rc			int
			

	if @CashSaleID is null or @UserID is null
	begin
		Select -1 'Return', 'Save without @Details is not possible' 'Error' 
		goto WithError
	end

	begin tran

	begin try

		select	@InvoiceNo = coalesce(max(InvoiceNo),0) + 1 
		from	CashSale.hlpInvoiceNumbers
		where	[Year] = YEAR(@now)

		insert into CashSale.hlpInvoiceNumbers (
				InvoiceNo,
				[Year],
				CashSaleID, 
				CreateOn, 
				UserID
				)
		select	@InvoiceNo,
				YEAR(@now),
				@CashSaleID,
				@now,
				@UserID

	end try
	begin catch
		Select -1 'InvoiceNo', ERROR_MESSAGE() 'Error' 
		goto WithError
	end catch


	commit

	select @InvoiceNo 'InvoiceNo', 'No Error' 'Error'
	
	return 0

WithError:
	if @@TRANCOUNT > 0
	begin
		set @logText = 'CashSale.GetInvoiceNumber: ' + cast(@CashSaleID as char(10))
		exec @rc = dbo.SaveLog
			@UserID = @UserID,
			@LogType = 'S',
			@LogArea = 'Bv',
			@LogDetails = @logText,
			@IsError = 1
		rollback tran
	end
	return -1

end